package com.hisoka.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.hisoka.domain.MailAuth;
import com.hisoka.domain.MailInfo;
import com.hisoka.repository.MailInfoRepos;
import com.hisoka.service.MailAuthService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

/**
 * @Auther hinsteny
 * @Date 2017-03-26
 * @copyright: 2017 All rights reserved.
 */
public class DBSendEamilJob extends EmailJobProcess {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private MailInfoRepos mailInfoRepos;

    @Resource
    private MailAuthService mailAuthService;

    /**
     * 根据分片信息去缓存中读取对应的发送邮件方账号
     * @param context
     * @return
     */
    @Override
    public MailAuth getMailAuth(ShardingContext context) {
        MailAuth auth = mailAuthService.getMailAuth(context.getShardingItem());
        return auth;
    }

    /**
     * 根据分片信息去缓存中读取对应的要发送的邮件记录
     * @param context
     * @return
     */
    @Override
    public MailInfo getMailInfo(ShardingContext context) {
        MailInfo mailInfo = mailInfoRepos.getById(new Long(1));
        logger.info("Query mail info by id=1, {}", mailInfo != null ? mailInfo.toString() : "NULL");
        return mailInfo;
    }

    @Override
    public boolean handleSuccess(MailInfo mailInfo) {
        logger.info("Send email to {} subject {} succeed!", mailInfo.getReceiver(), mailInfo.getSubject());
        return true;
    }

    @Override
    public boolean handleFail(MailInfo mailInfo) {
        logger.error("Send email to {} subject {} failed!", mailInfo.getReceiver(), mailInfo.getSubject());
        return true;
    }
}
